import React, { useEffect, useState } from 'react'
import { Button, Form, Input, Table, Popconfirm, Modal, InputNumber, message, Image } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'
import './index.less'
import { addMall, deleteMall, editMall, getMall, getMallByName } from '../../realApi'
import { SearchFormValues } from './types'



export default function Mall() {
  // 表格头部属性
  const columns:Record<string,any>[] = [
    {
      title: '商品名称',
      dataIndex: 'name',
      align: 'center',
      width: '7vw'
    },
    {
      title: '商品价格',
      dataIndex: 'price',
      align: 'center',
      width: '7vw'
    },
    {
      title: '商品图片',
      dataIndex: 'pic',
      render: (text: Record<string, any>, record: Record<string, any>) => (
        <div>
          <Image 
          src={record.pic} 
          style={{ height: 150 }} 
          fallback=""
          />
        </div>
      ),
      width: '20vw',
      align: 'center'
    },
    {
      title: '商品数量',
      dataIndex: 'count',
      align: 'center',
      width: '7vw'
    },
    {
      title: '商品描述',
      dataIndex: 'desc',
      align: 'center'
    },
    {
      title: '操作',
      align: 'center',
      width: '15vw',
      render: (rowData: Record<string, any>) => {
        return (
          <div>
            <Button icon={<EditOutlined />} style={{ marginRight: '5px' }} onClick={() => handleClick('edit', rowData)}>编辑</Button>
            <Popconfirm
              title="提示"
              description="此操作将删除该用户, 是否继续?"
              okText="确认"
              cancelText="取消"
              onConfirm={() => handleDelete(rowData)}
            >
              <Button icon={<DeleteOutlined />} type="primary" danger>删除</Button>
            </Popconfirm>
          </div>
        )
      }
    },
  ]

  // 表格数据
  const [tableData, setTableData] = useState<Record<string,any>[]>([])
  // 弹窗显示隐藏
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false)
  // 0 新增 1 编辑
  const [modalType, setModalType] = useState<number>(0)
  // 创建form实例
  const [form] = Form.useForm()

  // 页面渲染时获取表格数据
  useEffect(() => {
    getTableData()
  }, [])

  const getTableData = async () => {
    const { data: { data } } = await getMall()
    // console.log(data)
    setTableData(data)
  }

  // 新增和编辑按钮的回调函数
  const handleClick = (type: string, rowData?: Record<string, any>) => {
    setIsModalOpen(true)
    if (type === 'add') {
      setModalType(0)
    } else {
      setModalType(1)
      // 表单数据回填
      form.setFieldsValue(rowData)
    }
  }

  // 顶部搜索框的回调函数
  const handleFinish = async (e: SearchFormValues) => {
    const data = { name: e.keyword }
    if (!e.keyword) {
      getTableData()
      return message.open({
        type: 'warning',
        content: '搜索数据不能为空'
      })
    }
    const { data: { data: result } } = await getMallByName(data)
    if (result.length) {
      setTableData(result)
    }
    else {
      getTableData()
      return message.open({
        type: 'warning',
        content: '商品不存在'
      })
    }
  }

  // 表格删除行的回调函数
  const handleDelete = async (rowData: Record<string, any>) => {
    console.log(rowData)
    await deleteMall(rowData.id)
    getTableData()
    return message.open({
      type: 'success',
      content: '删除商品成功'
    })
  }

  // 弹窗确认的回调函数
  const handleOk = () => {
    // 表单校验
    form.validateFields().then((val) => {
      // 调接口
      if (modalType) { // 编辑
        editMall(val).then(() => {
          handleCancel()
          getTableData()
        })
      } else {
        addMall(val).then(() => {
          handleCancel()
          getTableData()
        })
      }
      return message.open({
        type: 'success',
        content: `${modalType ? "编辑" : "新增"}成功`
      })
    }).catch((err) => {
      return message.open({
        type: 'error',
        content: err
      })
    })
  }

  // 弹窗取消的回调函数
  const handleCancel = () => {
    setIsModalOpen(false)
    form.resetFields()
  }

  return (
    <div className='mall'>
      <div className='flex-box space-between'>
        <Button icon={<PlusOutlined />} type="primary" onClick={() => handleClick('add')}>新增</Button>
        <Form
          layout="inline"
          onFinish={handleFinish}
        >
          <Form.Item name="keyword" >
            <Input placeholder='请输入商品名称' />
          </Form.Item>
          <Form.Item>
            <Button htmlType='submit' type="primary">搜索</Button>
          </Form.Item>
        </Form>
      </div>
      <Table
        columns={columns}
        dataSource={tableData}
        rowKey={'id'}
        pagination={{
          defaultPageSize: 3
        }}
      />
      <Modal
        open={isModalOpen}
        title={modalType ? '编辑商品' : '新增商品'}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        width={600}
      >
        <Form
          form={form}
          labelCol={{
            span: 4
          }}
          wrapperCol={{
            span: 20
          }}
          labelAlign="left"
        >
          {
            modalType === 1 && <Form.Item
              name="id"
              hidden
            >
              <Input />
            </Form.Item>
          }
          <Form.Item
            label="商品名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入商品名称'
              },
              { pattern: /^[\u4E00-\u9FA5A-Za-z]+$/, message: '不支持数字,特殊字符或空格!' }
            ]}
          >
            <Input placeholder='请输入商品名称' />
          </Form.Item>
          <Form.Item
            label="商品价格"
            name="price"
            rules={[
              {
                required: true,
                message: '请输入商品价格'
              },
              {
                type: 'number',
                message: '商品价格必须是数字'
              }
            ]}
          >
            <InputNumber style={{ width: '8vw' }} placeholder='请输入商品价格' />
          </Form.Item>
          <Form.Item
            label="商品图片"
            name="pic"
            rules={[
              {
                required: true,
                message: '请输入商品图片链接'
              }
            ]}
          >
            <Input placeholder='请输入商品图片链接' />
          </Form.Item>
          <Form.Item
            label="商品数量"
            name="count"
            rules={[
              {
                required: true,
                message: '请输入商品数量'
              },
              {
                type: 'number',
                message: '商品数量必须是数字'
              }
            ]}
          >
            <InputNumber style={{ width: '8vw' }} placeholder='请输入商品数量' />
          </Form.Item>
          <Form.Item
            label="商品描述"
            name="desc"
            rules={[
              {
                required: true,
                message: '请输入商品描述'
              },
            ]}
          >
            <Input.TextArea placeholder='请输入商品描述' />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
